use std::collections::HashMap;

pub struct Solution;


impl Solution {
    pub fn frequency_sort(nums: Vec<i32>) -> Vec<i32> {
        let mut map = HashMap::new();
        nums.iter()
            .for_each(|v| {
                map.entry(*v)
                    .and_modify(|v| *v += 1)
                    .or_insert(1);
            });
        let mut vec = map
            .into_iter()
            .map(|(k, v)| (v, k))
            .collect::<Vec<(i32, i32)>>();
        vec.sort_by(|(k1, v1), (k2, v2)| (*k1).cmp(k2).then_with(|| (*v2).cmp(v1)));

        vec.iter()
            .flat_map(|(k1, v1)| vec![*v1; *k1 as usize])
            .collect::<Vec<i32>>()
    }
}